package com.wzapp.sitposture.authentication.pojo.converter;

import com.wzapp.sitposture.authentication.pojo.view.Bucket;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.AttributeConverter;
import java.io.IOException;

/**
 * Created by qianglong on 2018/1/15.
 */
public class BucketCoverterJson implements AttributeConverter<Bucket,String> {


    private static final Logger log = LoggerFactory.getLogger(BucketCoverterJson.class);

    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(Bucket meta) {
        try {
            return objectMapper.writeValueAsString(meta);
        } catch (JsonProcessingException ex) {
            log.error("JpaConverterJson convertToDatabaseColumn error." + ex.getMessage(),ex);
            return null;
        }
    }

    @Override
    public Bucket convertToEntityAttribute(String dbData) {
        try {
            return objectMapper.readValue(dbData, Bucket.class);
        } catch (IOException ex) {
            log.error("JpaConverterJson decoding json from database error." + dbData,ex);
            return null;
        }
    }

}
